<template>
  <view class="my-container">
    <!-- 用户信息区域 -->
    <view class="user-info-section">
      <view class="user-header">
        <image class="user-avatar" :src="userInfo.avatar" mode="aspectFill"></image>
        <view class="user-details">
          <text class="user-name">{{ userInfo.nickname }}</text>
          <text class="user-id">ID: {{ userInfo.userId }}</text>
        </view>
        <view class="user-actions">
          <view class="notification-icon-wrapper">
            <notification-icon></notification-icon>
          </view>
          <button class="edit-profile-btn" @click="editProfile">编辑资料</button>
        </view>
      </view>
      
      <view class="user-stats">
        <view class="stat-item" @click="navigateTo('/pages/user/followers')">
          <text class="stat-count">{{ userInfo.followersCount }}</text>
          <text class="stat-label">粉丝</text>
        </view>
        <view class="stat-item" @click="navigateTo('/pages/user/following')">
          <text class="stat-count">{{ userInfo.followingCount }}</text>
          <text class="stat-label">关注</text>
        </view>
        <view class="stat-item">
          <text class="stat-count">{{ userInfo.likesCount }}</text>
          <text class="stat-label">获赞</text>
        </view>
      </view>
    </view>
    
    <!-- 我的作品区域 -->
    <view class="my-works-section">
      <view class="section-header">
        <text class="section-title">我的作品</text>
        <text class="section-count">{{ worksCount }}件作品</text>
      </view>
      
      <!-- 作品分类标签 -->
      <view class="works-tabs">
        <view 
          class="tab-item" 
          v-for="(tab, index) in tabs" 
          :key="index"
          :class="{ active: currentTab === index }"
          @click="switchTab(index)"
        >
          {{ tab.name }}
        </view>
      </view>
      
      <!-- 作品列表 -->
      <view class="works-grid" v-if="filteredWorks.length > 0">
        <view 
          class="work-item" 
          v-for="(work, index) in filteredWorks" 
          :key="index"
          @click="goToDetail(work.id)"
        >
          <image class="work-image" :src="work.resultUrl" mode="aspectFill"></image>
          <view class="work-info">
            <view class="work-tags">
              <text class="work-tag" v-for="(tag, tagIndex) in ((work.tags && work.tags.length > 0) ? work.tags.slice(0, 2) : [])" :key="tagIndex">
                {{ tag }}
              </text>
              <!-- 如果没有标签，显示一个默认标签 -->
              <text class="work-tag" v-if="!work.tags || work.tags.length === 0">
                作品
              </text>
            </view>
            <view class="work-stats">
              <view class="work-stat">
                <text class="iconfont icon-like">❤️</text>
                <text>{{ work.likeCount }}</text>
              </view>
              <view class="work-stat">
                <text class="iconfont icon-comment">💬</text>
                <text>{{ work.commentCount }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 分页按钮 -->
      <view class="pagination" v-if="filteredWorks.length > 0">
        <button 
          class="prev-btn" 
          :disabled="pageParams.page <= 1"
          @click="loadPrevPage"
        >
          上一页
        </button>
        <text class="page-info">第 {{ pageParams.page }} 页</text>
        <button 
          class="next-btn" 
          :disabled="noMoreData"
          @click="loadNextPage"
        >
          下一页
        </button>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <image class="empty-image" src="/static/images/empty-works.png" mode="aspectFit"></image>
        <text class="empty-text">{{ getEmptyText() }}</text>
        <button class="create-btn" @click="navigateTo('/pages/create/create')">立即创作</button>
      </view>
    </view>
    
    <!-- 功能菜单区域 -->
    <view class="function-menu">
      <view class="menu-group">
        <view class="menu-item" @click="navigateTo('/pages/my/tasks')">
          <text class="menu-icon">🎨</text>
          <text class="menu-label">我的任务</text>
          <text class="menu-badge" v-if="processingTasksCount > 0">{{ processingTasksCount }}</text>
          <text class="menu-arrow">></text>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/my/history')">
          <text class="menu-icon">🕒</text>
          <text class="menu-label">浏览历史</text>
          <text class="menu-arrow">></text>
        </view>
      </view>
      
      <view class="menu-group">
        <view class="menu-item" @click="navigateTo('/pages/settings/settings')">
          <text class="menu-icon">⚙️</text>
          <text class="menu-label">设置</text>
          <text class="menu-arrow">></text>
        </view>
        <view class="menu-item" @click="showFeedback()">
          <text class="menu-icon">📝</text>
          <text class="menu-label">意见反馈</text>
          <text class="menu-arrow">></text>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/my/about')">
          <text class="menu-icon">ℹ️</text>
          <text class="menu-label">关于我们</text>
          <text class="menu-arrow">></text>
        </view>
      </view>
            
      <!-- 管理员菜单组 -->
      <view class="menu-group" v-if="userInfo.role === 'admin'">
        <view class="menu-group-title">管理员功能</view>
        <view class="menu-item" @click="navigateTo('/pages/admin/combinations')">
          <text class="menu-icon">🔄</text>
          <text class="menu-label">组合管理</text>
          <text class="menu-arrow">></text>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/admin/styles')">
          <text class="menu-icon">🎨</text>
          <text class="menu-label">风格管理</text>
          <text class="menu-arrow">></text>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/admin/style-categories')">
          <text class="menu-icon">📑</text>
          <text class="menu-label">风格类型管理</text>
          <text class="menu-arrow">></text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API接口
import api from '@/utils/api.js';
import taskApi from '@/utils/taskApi.js';
import NotificationIcon from '@/components/notification/NotificationIcon.vue';

export default {
  components: {
    NotificationIcon
  },
  data() {
    return {
      worksCount: 0,
      // 用户信息
      userInfo: {
        userId: '',
        nickname: '',
        avatar: '',
        followersCount: 0,
        followingCount: 0,
        likesCount: 0
      },
      
      // 标签页
      tabs: [
        { name: '全部', filter: null },
        { name: '最新', filter: 'latest' },
        { name: '最热', filter: 'popular' }
      ],
      currentTab: 0,
      
      // 我的作品
      myWorks: [],
      myTasks: [],
      processingTasksCount: 0,
      // 加载状态
      loading: false,
      // 错误信息
      error: '',
      // 分页参数
      pageParams: {
        page: 1,
        size: 10,
        filter: null
      },
      noMoreData: false
    }
  },
  
  computed: {
    // 根据当前标签过滤作品
    filteredWorks() {
      const filter = this.tabs[this.currentTab].filter;
      
      if (!filter) return this.myWorks;
      
      switch (filter) {
        case 'latest':
          return [...this.myWorks].sort((a, b) => 
            new Date(b.createTime) - new Date(a.createTime)
          );
        case 'popular':
          return this.myWorks.filter(work => work.likeCount > 50); // 假设点赞数超过50为热门
        case 'favorite':
          return this.myWorks.filter(work => work.isFavorite);
        default:
          return this.myWorks;
      }
    }
  },
  
  onLoad() {
    this.initData();
  },

  onShow() {
    this.initData();
  },
  
  onPullDownRefresh() {
    this.refreshData();
  },
  
  onReachBottom() {
    this.loadMoreWorks();
  },
  
  methods: {
    // 初始化数据
    initData() {
      this.isLoading = true;
      
      // 先加载用户信息
      this.loadUserInfo()
        .then(() => {
          // 再加载作品和任务
          return Promise.all([
            this.loadMyWorks(true)
          ]);
        })
        .finally(() => {
          this.isLoading = false;
          
          // 停止下拉刷新
          uni.stopPullDownRefresh();
        });
    },
    
    // 刷新数据
    refreshData() {
      this.isRefreshing = true;
      
      Promise.all([
        this.loadUserInfo(),
        this.loadMyWorks(true),
      ]).finally(() => {
        this.isRefreshing = false;
        
        // 停止下拉刷新
        uni.stopPullDownRefresh();
      });
    },
    
    // 加载用户信息
    loadUserInfo() {
      this.loading = true;
      
      return api.user.getUserInfo()
        .then(res => {
          if (res.code === 200) {
            const userData = res.data;
            this.userInfo = {
              userId: userData.id,
              nickname: userData.nickname || userData.username,
              avatar: userData.avatar || '/static/images/default-avatar.png',
              followersCount: 0,
              followingCount: 0,
              likesCount: 0,
              role: userData.role
            };
            
            // 获取粉丝数量
            api.user.getFollowers().then(followersRes => {
              if (followersRes.code === 200) {
                this.userInfo.followersCount = followersRes.data.length || 0;
              }
            }).catch(err => {
              console.error('获取粉丝数量失败', err);
            });
            
            // 获取关注数量
            api.user.getFollowing().then(followingRes => {
              if (followingRes.code === 200) {
                this.userInfo.followingCount = followingRes.data.length || 0;
              }
            }).catch(err => {
              console.error('获取关注数量失败', err);
            });
            
            // 获取获赞数量
            api.user.getUserReceivedLikesCount().then(likesRes => {
              if (likesRes.code === 200) {
                this.userInfo.likesCount = likesRes.data || 0;
              }
            }).catch(err => {
              console.error('获取获赞数量失败', err);
            });
          
          } else {
            this.error = res.message || '获取用户信息失败';
            uni.showToast({
              title: this.error,
              icon: 'none'
            });
          }
        })
        .catch(err => {
          this.error = '获取用户信息失败';
          uni.showToast({
            title: this.error,
            icon: 'none'
          });
          console.error('获取用户信息失败', err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 加载我的作品
    loadMyWorks(refresh = false) {
      // 如果已经在加载中，则不重复请求
      if (this.loading) {
        return Promise.resolve();
      }
      
      // 如果已加载全部数据且不是刷新操作，则不再请求
      // if (this.noMoreData && !refresh) {
      //   return Promise.resolve();
      // }
      
      this.loading = true;
      
      // 如果是刷新操作，重置页码
      if (refresh) {
        this.pageParams.page = 1;
        this.noMoreData = false;
      }
      
      // 构建查询参数
      const params = {
        page: this.pageParams.page,
        size: this.pageParams.size,
        filter: this.tabs[this.currentTab].filter,
        userId: this.userInfo.userId // 添加用户ID
      };
      
      return api.user.getUserWorks(params)
        .then(res => {
          if (res.code === 200 && res.data) 
          {
            this.worksCount = res.data.total;
            // 转换后端数据格式为前端所需格式
            const works = (res.data.list || []).map(work => {
              return {
                id: work.id,
                originalUrl: work.originalImage,
                resultUrl: work.resultImage,
                tags: Array.isArray(work.tags) ? work.tags : (work.tags ? work.tags.split(',') : []),
                likeCount: work.likeCount || 0,
                commentCount: work.commentCount || 0,
                createTime: work.createTime,
                isPopular: (work.likeCount || 0) > 50, // 假设点赞数超过50为热门
                isFavorite: work.isFavorite || false
              };
            });
            
            // 直接替换数据，不再追加
            this.myWorks = works;
            // 判断是否已加载全部数据
            if (works.length < this.pageParams.size) {
              this.noMoreData = true;
            } else {
              // 不再自动增加页码，由loadNextPage方法控制
              this.noMoreData = false;
            }
          } else {
            this.error = res.message || '获取作品列表失败';
            uni.showToast({
              title: this.error,
              icon: 'none'
            });
          }
        })
        .catch(err => {
          this.error = '获取作品列表失败';
          uni.showToast({
            title: this.error,
            icon: 'none'
          });
          console.error('获取作品列表失败', err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 加载更多作品
    loadMoreWorks() {
      if (!this.loading) {
        this.loadMyWorks();
      }
    },
    
    // 切换标签
    switchTab(index) {
      if (this.currentTab !== index) {
        this.currentTab = index;
        this.pageParams.page = 1;
        this.loadMyWorks(true);
      }
    },
    
    // 获取空状态文本
    getEmptyText() {
      const filter = this.tabs[this.currentTab].filter;
      
      switch (filter) {
        case 'latest':
          return '你还没有创作作品';
        case 'popular':
          return '你还没有热门作品，继续加油吧';
        case 'favorite':
          return '你还没有收藏作品';
        default:
          return '你还没有创作作品';
      }
    },
    
    // 编辑个人资料
    editProfile() {
      uni.navigateTo({
        url: '/pages/my/profile-edit'
      });
    },
    
    // 跳转到作品详情
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${id}`
      });
    },
    
    // 页面导航
    navigateTo(url) {
      // 判断是否是 tabBar 页面
      const tabBarPages = ['/pages/feed/feed', '/pages/create/create', '/pages/my/my','/pages/my/tasks'];
      if (tabBarPages.includes(url)) {
        uni.switchTab({ url });
      } else {
        uni.navigateTo({ url });
      }
    },
    
    // 显示反馈弹窗
    showFeedback() {
      uni.showModal({
        title: '意见反馈',
        content: '感谢您的使用，如有任何问题或建议，请联系我们的客服团队。',
        confirmText: '联系客服',
        cancelText: '关闭',
        success: (res) => {
          if (res.confirm) {
            // 跳转到客服页面或复制客服联系方式
            uni.setClipboardData({
              data: 'support@aistyle.com',
              success: () => {
                uni.showToast({
                  title: '客服邮箱已复制',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },
    
    // 加载上一页
    loadPrevPage() {
      if (this.pageParams.page > 1) {
        this.pageParams.page--;
        this.loadMyWorks();
      }
    },
    
    // 加载下一页
    loadNextPage() {
      if (!this.noMoreData) {
        this.pageParams.page++;
        this.loadMyWorks();
      }
    }
  }
}
</script>

<style>
.my-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 用户信息区域 */
.user-info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.user-header {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 150rpx;
  height: 150rpx;
  border-radius: 50%;
  margin-right: 30rpx;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.user-id {
  font-size: 26rpx;
  color: #999;
  display: block;
}

.user-actions {
  display: flex;
  align-items: center;
}

.notification-icon-wrapper {
  margin-right: 20rpx;
}

.edit-profile-btn {
  background-color: #f5f5f5;
  color: #666;
  font-size: 26rpx;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
}

.user-stats {
  display: flex;
  margin-top: 40rpx;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-count {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 26rpx;
  color: #999;
}

/* 我的作品区域 */
.my-works-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-count {
  font-size: 26rpx;
  color: #999;
}

.works-tabs {
  display: flex;
  border-bottom: 1rpx solid #f5f5f5;
  margin-bottom: 30rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 20rpx 0;
  position: relative;
}

.tab-item.active {
  color: #FF69B4;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #FF69B4;
  border-radius: 2rpx;
}

.works-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.work-item {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.work-image {
  width: 100%;
  height: 400rpx;
  border-radius: 12rpx 12rpx 0 0;
}

.work-info {
  padding: 15rpx;
}

.work-tags {
  display: flex;
  margin-bottom: 10rpx;
}

.work-tag {
  font-size: 22rpx;
  color: #FF69B4;
  background-color: rgba(255, 105, 180, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
}

.work-stats {
  display: flex;
}

.work-stat {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
}

.work-stat .iconfont {
  font-size: 28rpx;
  margin-right: 6rpx;
}

/* 分页按钮 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

.prev-btn, .next-btn {
  background-color: #f5f5f5;
  color: #666;
  font-size: 26rpx;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  margin: 0 20rpx;
}

.prev-btn:disabled, .next-btn:disabled {
  background-color: #ddd;
  color: #999;
}

.page-info {
  font-size: 26rpx;
  color: #666;
  margin: 0 20rpx;
}

/* 空状态 */
.empty-state {
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.create-btn {
  background-color: #FF69B4;
  color: #fff;
  font-size: 28rpx;
  padding: 15rpx 40rpx;
  border-radius: 40rpx;
}

/* 功能菜单区域 */
.function-menu {
  background-color: #fff;
}

.menu-group {
  margin-bottom: 20rpx;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.menu-label {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.menu-badge {
  font-size: 24rpx;
  color: #FF69B4;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  background-color: rgba(255, 105, 180, 0.1);
  margin-right: 10rpx;
}

.menu-arrow {
  font-size: 28rpx;
  color: #ccc;
}


.menu-group-title {
  padding: 20rpx 30rpx 10rpx;
  font-size: 24rpx;
  color: #999;
  background-color: #f8f8f8;
}
</style>
